package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.massage.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;

    @Value("${file.oss.web-site}")
    String webSite;


    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 频道id
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //文章状态
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        // 当前自媒体人文章
        // 如果用户为空提示登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        //3 执行查询
        IPage<WmNews> resultPage = page(page, lambdaQueryWrapper);
        //4 返回封装查询结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(), resultPage.getRecords());

        // 处理文章图片
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {

        // 1 参数校验
        if (StringUtils.isNotBlank(wmNewsDto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        // 2 判断文章状态
        Short status = wmNewsDto.getStatus();
        if (status == null || (status.intValue() != 1 && status.intValue() != 0)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章状态错误");
        }
        //判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.2 基于dto创建wm_news
        WmNews wmNews = new WmNews();
        // 拷贝属性
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        // 1.3 如果type=-1 将type暂时设置为null  避免保存出错
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
            wmNews.setType(null);
        }
        // 1.4 如果传入的images集合不为空  转为字符串  用逗号拼接
        if (CollectionUtils.isNotEmpty(wmNewsDto.getImages())) {
            String imagesStr = imagesListToStr(wmNewsDto.getImages());
            wmNews.setImages(imagesStr);
        }
        wmNews.setId(user.getId());
        // 2. 保存或修改WmNews
        saveOrUpdateWmNews(wmNews);
        // 3.如果是待审核状态 需要保存 内容图片和封面图片 与素材的关联关系
        if (status.intValue() == 0) {
            return ResponseResult.okResult();
        }
            // TODO 3.1 抽取文章中关联的图片路径
        List<Map> contents = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        List<String> materials = parseContentImages(contents);
        // TODO 3.2 关联文章内容中的图片和素材关系
        if (CollectionUtils.isNotEmpty(materials)) {
            savePictureMaterial(materials, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // TODO 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveCoverMaterial(materials, wmNews, wmNewsDto);
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult findWmNewsById(Integer id) {
       //检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您要查询的文章不存在");
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您要查询的文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章不允许被删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getId, wmNews.getId())
        );
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 接口描述**: 文章上下架操作
     * **接口地址**:`/api/v1/news/down_or_up`
     * **请求方式**:`POST`
     *
     * @return
     */

    @Autowired
    KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //校验参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
      // 1.根据文章内容查询到文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您要操作的文章不存在");
        }
        // 2.查询文章状态
        //判断文章当前状态是否可以被上下架
        if (wmNews.getStatus() != WmNews.Status.PUBLISHED.getCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章已被上架");
        }
      // 3.修改文章状态，同步到app端（后期做）TODO
        if (dto.getLabels() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            update(Wrappers.<WmNews>lambdaUpdate()
                    .eq(WmNews::getId, dto.getId())
                    .set(WmNews::getEnable, dto.getEnable())
            );
        }



        //1.检查参数
        //2.查询文章
        //3.判断文章是否发布
        //4.修改文章状态，同步到app端（后期做）TODO
        // ***发消息
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("enable", dto.getEnable());
            map.put("articleId", wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    @Override
    public ResponseResult<List<Integer>> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间获取ID

        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8)
                .select(WmNews::getId)
                //获取到的id封装到集合中并返回
        );
        List<Integer> idList = list.stream().map(WmNews::getId)
                .collect(Collectors.toList());
        return ResponseResult.okResult(idList);

    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
      // 查询文章列表
      // 1.检查参数
        dto.checkParam();
      // 2.记录当前页
        Integer dtoPage = dto.getPage();
        // 3.设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
      // 4.分页查询：接口调用方法
        List<WmNewsVo> listAndPageVo = wmNewsMapper.findListAndPage(dto);
        // 5.统计数据一共多少条
        long listCount = wmNewsMapper.findListCount(dto);
        // 6.返回结果
        PageResponseResult result = new PageResponseResult(dtoPage, dto.getSize(), listCount, listAndPageVo);
        result.setHost(webSite);
        return result;

    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
      // 查询文章详情
      // 1.检查参数：id不能为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "查询的id不能为空");
        }
      // 2.根据拿到的id查询文章信息,对拿到的参数进行判断
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您要查询的数据不存在");
        }
        // 3.查询文章作者：作者不能为空，所以要判断
        WmUser wmUser = null;
        if (wmNews.getUserId()!=null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
      // 4.封装信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        // 4.1将文章内容拷贝到展示的实体类上
        BeanUtils.copyProperties(wmNews, wmNewsVo);
      // 4.2设置作者姓名
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }
      // 4.3返回实体类对象
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        // 4.4返回集合
        return responseResult;
    }

    /**
     * 修改文章状态
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.修改文章的状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
      return   ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }



    private void saveCoverMaterial(List<String> materials, WmNews wmNews, WmNewsDto wmNewsDto) {
        // 封面的图片列表
        List<String> images = wmNewsDto.getImages();
        // 封面自动生成
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            // 如果内容url为空  设置为无图模式
            if (CollectionUtils.isNotEmpty(materials)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            } else if (materials.size() <= 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imagesListToStr(images));
            }
            updateById(wmNews);
        }
        // 保存封面和素材的关联关系
        if (CollectionUtils.isNotEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());
            savePictureMaterial(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());//创建时间
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);

        if (wmNews.getId() != null) {
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getId, wmNews.getId()));
            //根据ID跟新wmNews
            updateById(wmNews);
        }
        save(wmNews);
    }

    private void savePictureMaterial(List<String> materialUrls, Integer newsId, Short type) {
        List<WmMaterial> wmNewsMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                                    .in(WmMaterial::getUrl,materialUrls)
                                    .eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId())
        );
        if (CollectionUtils.isNotEmpty(wmNewsMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用的素材不存在");
        }
    }

    private String imagesListToStr(List<String> images) {
        return images.stream()
                .map(str -> str.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));
    }

    private List<String> parseContentImages(List<Map> contents) {
        // 过滤type=image所有的集合
        return contents.stream().filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x->(String)x.get("value"))
                // 图片url去除前缀
                .map(url -> url.replace(webSite, "").replace(" ",""))
                // sretam 转成list集合
                .collect(Collectors.toList());
    }

}

